from django.db.models.functions import datetime
import datetime
from django.shortcuts import render

# Create your views here.
from app.models.index import Index
from app.models.order import Orders
from app.models.user import User
from collections import Counter


# 获取本周一时间
def get_this_week():
    today = datetime.datetime.now()
    miss_day = today.weekday()
    if miss_day != 0:
        miss = datetime.timedelta(days=miss_day)
        today -= miss
    monday_str = today.strftime("%Y-%m-%d")
    return datetime.datetime.strptime(monday_str, "%Y-%m-%d")


def index(request):
    today = datetime.datetime.now()
    # 年
    start_time_year = datetime.datetime.strptime(str(today.year), "%Y")
    year_num = Index.objects.filter(visit_time__gt=start_time_year).count()
    # 月
    start_time_month = '%d-%02d-01' % (today.year, today.month)
    month_num = Index.objects.filter(visit_time__gt=start_time_month).count()
    # 周
    start_time_week = get_this_week()
    week_num = Index.objects.filter(visit_time__gt=start_time_week).count()
    # 日
    start_time_day = today - datetime.timedelta(hours=today.hour, minutes=today.minute, seconds=today.second,
                                                microseconds=today.microsecond)
    day_num = Index.objects.filter(visit_time__gt=start_time_day).count()
    #
    address = []
    for e in Orders.objects.all():
        address.append(e.point)
    address = Counter(address).most_common(3)
    order_num = Orders.objects.all().count()
    user_num = User.objects.all().count()
    sale_num = Orders.objects.filter(status='已完成').sum('payment')

    sessionName = request.session.get('session_name', None)
    context = {
        "order_num": order_num,
        "user_num": user_num,
        "sale_num": sale_num,
        "address": address,
        "year_num": year_num,
        "month_num": month_num,
        "week_num": week_num,
        "day_num": day_num,
        'sessionName': sessionName

    }
    return render(request, 'visites/temp-index.html', context)
